package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.ListMapper;
import com.goods.business.mapper.ProductStockMapper;
import com.goods.business.service.ProductStockService;
import com.goods.common.model.business.Product;
import com.goods.common.model.business.ProductStock;
import com.goods.common.vo.business.ProductStockVO;
import com.goods.common.vo.business.ProductVO;
import com.goods.common.vo.system.PageVO;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductStockServiceImpl implements ProductStockService {
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private ListMapper listMapper;

    // 查询所有的库存
    @Override
    public List<ProductStockVO> findAllStocks(Integer pageNum, Integer pageSize) {
        List<Product> products = listMapper.selectAll();
        return getProductStockVOS(products);
    }

    // 查询商品库存
    @Override
    public PageVO<ProductStockVO> findProductStocks(Integer pageNum, Integer pageSize) {
        List<Product> products = listMapper.selectAll();

        List<ProductStockVO> productStockVOList = getProductStockVOS(products);

        PageHelper.startPage(pageNum,pageSize);
        PageInfo pageInfo = new PageInfo(productStockVOList);
        PageVO<ProductStockVO> tPageVO = new PageVO(pageInfo.getTotal(), productStockVOList);
        return tPageVO;
    }

    // 根据商品集合 转换 商品返回页面的数据
    private List<ProductStockVO> getProductStockVOS(List<Product> products) {
        List<ProductStockVO> productStockVOList = new ArrayList<>();
        for (Product product : products) {
            // 商品编号
            String pNum = product.getPNum();
            // 返回对象
            ProductStockVO productStockVO = new ProductStockVO();
            // 去商品库中查询库存
            ProductStock productStock = new ProductStock();
            productStock.setPNum(pNum);
            productStock = productStockMapper.selectOne(productStock);
            // 获取商品对应的库存数量
            if(productStock!=null){
                productStockVO.setStock(productStock.getStock());
            }else{
                productStockVO.setStock(Long.valueOf(0));
            }
            // 将商品信息复制到返回对象中
            BeanUtils.copyProperties(product,productStockVO);
            productStockVOList.add(productStockVO);
        }
        return productStockVOList;
    }
}
